//
//  WeChatMomentDemoViewController.swift
//  Example
//
//  Created by long on 2021/2/3.
//

import UIKit
import Photos
import ZLPhotoBrowser

import SwiftyJSON


let roomCount = 2
let bedroomCount = 2
let toiletCount = 2

class WeChatMomentDemoViewController: UIViewController {
    
    var resultClosure: SSResultClosure?     // 闭包

    //客厅
    @IBOutlet weak var titleLab: UILabel!
    @IBOutlet weak var firstPartView: SSWechatView!
    
    //厨房
    @IBOutlet weak var titleLab2: UILabel!
    @IBOutlet weak var secondPartView: SSWechatView!
    
    //卫生间
    @IBOutlet weak var titleLab3: UILabel!
    @IBOutlet weak var thirdPartView: SSWechatView!
    
    var totals = [SSImageModel]()
    var imgUrls = [[String:AnyObject]]()
    var orderNo = ""//订单号
    var type = ""//1 开始打卡 2结束打卡
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupUIS()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        firstPartView.collectionView.frame = CGRect(x: 0, y: 0, width: firstPartView.frame.width, height: firstPartView.frame.height)
        secondPartView.collectionView.frame = CGRect(x: 0, y: 0, width: secondPartView.frame.width, height: secondPartView.frame.height)
        thirdPartView.collectionView.frame = CGRect(x: 0, y: 0, width: thirdPartView.frame.width, height: thirdPartView.frame.height)
    }
    
   
    
    func setupUIS() {
        self.titleLab.text = "客厅  0/\(roomCount)"
        firstPartView.numberResult { number in
            self.titleLab.text = "客厅  \(number)/\(roomCount)"
        }
        
        self.titleLab2.text = "卫生间  0/\(toiletCount)"
        secondPartView.numberResult { number in
            self.titleLab2.text = "卫生间  \(number)/\(toiletCount)"
        }
        
        self.titleLab3.text = "卧室  0/\(bedroomCount)"
        thirdPartView.numberResult { number in
            self.titleLab3.text = "卧室  \(number)/\(bedroomCount)"
        }
        
        view.backgroundColor = UIColor(hex: "EBF4FD")
     
 
        rightNav()
    }
    
    func rightNav() {
        

        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(UIColor.black, for: .normal)
//        btn.setImage(UIImage(named: "headset_nav"), for: .normal)
        btn .addTarget(self, action: #selector(rightNavAcion), for: .touchUpInside)
        let rightItem = UIBarButtonItem(customView: btn)
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    func resultClosure(_ finished: @escaping SSResultClosure) {
        resultClosure = finished
    }
    
    @objc func rightNavAcion(){
        clockIn()
    }
    
    @IBAction func submitAction(_ sender: Any) {
        if(firstPartView.images.count < roomCount){
            view.makeToast("客厅图片不能少于\(roomCount)张")
            return
        }
        if(secondPartView.images.count < toiletCount){
            view.makeToast("卫生间图片不能少于\(toiletCount)张")
            return
        }
        if(thirdPartView.images.count < bedroomCount){
            view.makeToast("卧室图片不能少于\(bedroomCount)张")
            return
        }
        
        handleImage()
    }
    
    //把图片转成对象
    func handleImage() {
        var totals = [SSImageModel]()
        for(_,item) in firstPartView.images.enumerated(){
            let m = SSImageModel()
            m.image = item
            m.imgArea = "1"
            totals.append(m)
        }
        
        for(_,item) in secondPartView.images.enumerated(){
            let m = SSImageModel()
            m.image = item
            m.imgArea = "2"
            totals.append(m)
        }
        
        for(_,item) in thirdPartView.images.enumerated(){
            let m = SSImageModel()
            m.image = item
            m.imgArea = "3"
            totals.append(m)
        }
        
        self.totals = totals
        
        uploadImg()
    }
    
    

    
}



extension WeChatMomentDemoViewController{
    //上传图片
    func uploadImg() {
        
        SSProgressHUD.share.show()
        
        let group = DispatchGroup()
        for item in self.totals{
            group.enter()
            uploadImage(url: APIUrl.share.empUploadImg_URL, image: item.image, params: [:]) { result, error in
                // 将当前下载操作从组中移除
                if let _ = result{
                    let json = JSON(parseJSON: result!)
                    let data = json["data"].dictionary
                    item.imgUrl = data!["imgPath"]!.stringValue
                    print("")
                    group.leave()

                }else{
                    group.leave()

                }
            }
        }
        // 监听下载操作
        group.notify(queue: DispatchQueue.main) { [self] in
            print("main queue execute!")
            var imgUrls = [[String:AnyObject]]()
            for item in self.totals{
                let dic = [
                    "imgArea":item.imgArea,
                    "imgUrl":item.imgUrl,
                ] as! [String:AnyObject]
                imgUrls.append(dic)
                self.imgUrls = imgUrls
            }
            
            print("--\(imgUrls)")
            print("--")
            submitNetWorking()
        }
    }
    
    func submitNetWorking() {
        let params = [
            "orderNo": self.orderNo,
            "type": self.type,
            "phoneNo":kUserPhone,
            "listImg": self.imgUrls
                ] as! [String:AnyObject]
        HttpConnectTools.share.request(urlString: APIUrl.share.empCLockIn_URL, parameters: params) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    self.view.makeToast("打卡成功")
                    self.resultClosure!()
                    self.navigationController?.popViewController(animated: true)
                }else{
                    dissmissToTast(msg: retMsg)
                }
            }
        }
    }
    
    //快捷打卡
    func clockIn() {
        let params = [
            "orderNo": self.orderNo,
            "type": type,
            "phoneNo":kUserPhone
                ] as! [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.empCLockIn_URL, parameters: params) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    self.view.makeToast("打卡成功")
                    self.resultClosure!()
                    self.navigationController?.popViewController(animated: true)
                }else{
                    dissmissToTast(msg: retMsg)
                }
            }
        }
    }
    
}


class SSImageModel: NSObject {
    var image: UIImage = UIImage()
    var imgArea: String = ""
    var imgUrl: String = ""
    
    required override init() {}
}




